#include "gamewindow.h"
#include "ui_gamewindow.h"

const int GRID_SIZE = 20;
const int GAME_WIDTH = 30;
const int GAME_HEIGHT = 25;
const int MIN_SPEED = 50;    // 最快速度（毫秒）
const int MAX_SPEED = 300;   // 最慢速度（毫秒）
const int SPEED_STEP = 20;   // 每次调整的步长（毫秒）

GameWindow::GameWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::GameWindow)
{
    ui->setupUi(this);
    setFixedSize(GAME_WIDTH * GRID_SIZE, GAME_HEIGHT * GRID_SIZE);

    gameSpeed = 150;  // 初始速度
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &GameWindow::updateGame);
    timer->start(gameSpeed);

    // 初始化蛇
    snake.append(QPoint(GAME_WIDTH / 2, GAME_HEIGHT / 2));
    snake.append(QPoint(GAME_WIDTH / 2 - 1, GAME_HEIGHT / 2));
    snake.append(QPoint(GAME_WIDTH / 2 - 2, GAME_HEIGHT / 2));

    direction = 1; // 初始向右
    gameOver = false;
    score = 0;

    if (!loadResources()) {
        qDebug() << "部分图片加载失败，将使用默认图形";
    }

    generateFood();
}

GameWindow::~GameWindow()
{
    delete ui;
}

bool GameWindow::loadResources()
{
    bool foodLoaded = foodImage.load(":/images/food.png");
    if (!foodLoaded || foodImage.isNull()) {
        qDebug() << "加载食物图片失败，路径可能有误或格式不支持";
        foodImage = QPixmap(GRID_SIZE, GRID_SIZE);
        foodImage.fill(Qt::transparent);

        QPainter painter(&foodImage);
        painter.setRenderHint(QPainter::Antialiasing);
        painter.setBrush(Qt::red);
        painter.drawEllipse(0, 0, GRID_SIZE, GRID_SIZE);
        painter.end();
    } else {
        foodImage = foodImage.scaled(GRID_SIZE, GRID_SIZE, Qt::KeepAspectRatio);
    }

    bool bgLoaded = backgroundImage.load(":/images/background.png");
    if (!bgLoaded || backgroundImage.isNull()) {
        qDebug() << "加载背景图片失败，路径可能有误或格式不支持";
        backgroundImage = QPixmap(width(), height());
        backgroundImage.fill(Qt::black);
    } else {
        backgroundImage = backgroundImage.scaled(width(), height(), Qt::KeepAspectRatioByExpanding);
    }

    return foodLoaded && bgLoaded;
}
void GameWindow::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    
    QPainter painter(this);
    
    // 绘制背景
    painter.drawPixmap(0, 0, backgroundImage);
    
    // 绘制蛇
    painter.setBrush(Qt::green);
    for (const auto& segment : snake) {
        painter.drawRect(segment.x() * GRID_SIZE, segment.y() * GRID_SIZE, 
                         GRID_SIZE - 1, GRID_SIZE - 1);
    }
    
    // 绘制食物
    painter.drawPixmap(food.x() * GRID_SIZE, food.y() * GRID_SIZE, foodImage);
    
    // 游戏结束文字
    if (gameOver) {
        painter.setPen(Qt::white);
        painter.setFont(QFont("Arial", 20));
        painter.drawText(rect(), Qt::AlignCenter, 
                        QString("游戏结束！得分: %1\n按空格键重新开始").arg(score));
    }
    
    // 绘制分数和速度
    painter.setPen(Qt::white);
    painter.setFont(QFont("Arial", 12));
    
    // 分数显示
    painter.fillRect(5, 5, 80, 25, QColor(0, 0, 0, 128));
    painter.drawText(10, 20, QString("分数: %1").arg(score));
    
    // 速度显示（修正为显示速度级别，数值越大表示越快）
    int speedLevel = 100 - ((gameSpeed - MIN_SPEED) * 100 / (MAX_SPEED - MIN_SPEED));
    painter.fillRect(5, 35, 100, 25, QColor(0, 0, 0, 128));
    painter.drawText(10, 50, QString("速度: %1%").arg(speedLevel));
}

void GameWindow::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case Qt::Key_Up:
        if (direction != 2) direction = 0;
        break;
    case Qt::Key_Right:
        if (direction != 3) direction = 1;
        break;
    case Qt::Key_Down:
        if (direction != 0) direction = 2;
        break;
    case Qt::Key_Left:
        if (direction != 1) direction = 3;
        break;
    case Qt::Key_Space:
        if (gameOver) {
            // 重置游戏
            snake.clear();
            snake.append(QPoint(GAME_WIDTH / 2, GAME_HEIGHT / 2));
            snake.append(QPoint(GAME_WIDTH / 2 - 1, GAME_HEIGHT / 2));
            snake.append(QPoint(GAME_WIDTH / 2 - 2, GAME_HEIGHT / 2));
            direction = 1;
            gameOver = false;
            score = 0;
            gameSpeed = 150;  // 重置速度
            timer->start(gameSpeed);
            generateFood();
        }
        break;
    case Qt::Key_W:  // 加速
        adjustSpeed(-SPEED_STEP);
        break;
    case Qt::Key_S:  // 减速
        adjustSpeed(SPEED_STEP);
        break;
    }
}

void GameWindow::updateGame()
{
    if (gameOver) return;
    
    // 获取蛇头位置
    QPoint head = snake.first();
    
    // 根据方向移动蛇头
    switch (direction) {
    case 0: // 上
        head.setY(head.y() - 1);
        break;
    case 1: // 右
        head.setX(head.x() + 1);
        break;
    case 2: // 下
        head.setY(head.y() + 1);
        break;
    case 3: // 左
        head.setX(head.x() - 1);
        break;
    }
    
    // 检查是否碰撞边界
    if (head.x() < 0 || head.x() >= GAME_WIDTH || 
        head.y() < 0 || head.y() >= GAME_HEIGHT) {
        gameOver = true;
        update();
        return;
    }
    
    // 检查是否碰撞自身
    if (snake.contains(head)) {
        gameOver = true;
        update();
        return;
    }
    
    // 将新头添加到蛇身
    snake.prepend(head);
    
    // 检查是否吃到食物
    if (head == food) {
        score += 10;
        generateFood();
    } else {
        // 没吃到食物则移除尾部
        snake.removeLast();
    }
    
    update();
}

void GameWindow::generateFood()
{
    // 生成不在蛇身上的食物位置
    do {
        food.setX(QRandomGenerator::global()->bounded(GAME_WIDTH));
        food.setY(QRandomGenerator::global()->bounded(GAME_HEIGHT));
    } while (snake.contains(food));
}

// 调整游戏速度
void GameWindow::adjustSpeed(int delta)
{
    // 计算新速度并限制在合理范围内
    gameSpeed = qBound(MIN_SPEED, gameSpeed + delta, MAX_SPEED);
    
    // 更新定时器间隔
    timer->setInterval(gameSpeed);
    
    qDebug() << "速度调整为:" << gameSpeed << "ms";
}    
